//
//  BLESetSecretVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/2.
//

#import "BLESetSecretVC.h"
#import "CBLECenterMnger.h"
#import <YYAnimatedImageView.h>
#import <YYImage/YYImage.h>
#import "YYText.h"
#import "RHBaseWebViewController.h"
#import "CDZQRScanViewController.h"
#import "RHNavigationController.h"
#import "BLEConnectClouldVC.h"
#import "CBLECenterMnger.h"
#import "CBLEDataParse.h"
#import "NSString+YYUtil.h"
#import "RHLocalSettingTypeModel.h"

@interface BLESetSecretVC ()

@property (nonatomic, strong) YYAnimatedImageView  *gifImg;

@property (nonatomic ,strong) QMUITextField *secretTextField;

@property (nonatomic ,strong) QMUIButton *agreeBtn;

@property (nonatomic ,strong) UIView *tipsView;

@property (nonatomic ,copy) NSString *deviceId;
@end

@implementation BLESetSecretVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设置密钥".rh_localized;
    self.deviceId = [CBLECenterMnger shareMnger].curPheral.deviceId;
    [self setupUI];
    [self createCmd];
//    [self checkDeviceId];
}

//-(void)checkDeviceId
//{
//    if(self.deviceId.length>0){
//        [self getDeviceSecret];
//    }
//    else{
//        //从蓝牙获取设备id,再从后台获取设备秘钥
//        [[RHBleCmdManager shareMnger]readDeviceInfoWithCmdModel:[self.cmdArray firstObject]];
//    }
//}
//
//-(void)getDeviceSecret
//{
//    //从后台获取设备秘钥
//   
//    [BaseModel startGetWithCompletionAPIKey:H_getDevicePassword argument:@{@"deviceId":ValidNullData(self.deviceId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        NSString *pwd = ValidNullData(request.responseJSONObject[@"data"][@"password"]);
//        self.secret =  [NSString  base64Decode:pwd];
//        self.secretTextField.text = self.secret;
//                
//    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        
//    }];
// 
//}

-(void)createCmd
{
    NSArray *cmdArr = @[@{
        @"field":@"Ems_CdDevId",
        @"regAddr":@(3035),
        @"bitWidth":@(320),
        @"type":@"text",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_ClDevK",
        @"regAddr":@(3015),
        @"bitWidth":@(320),
        @"type":@"text",
        @"cmdType":@(LocalSettingType_EMS)
    }];
    
    self.cmdArray =  [NSArray yy_modelArrayWithClass:[RHLocalSettingModel class] json:cmdArr];
}


-(void)receiveDeviceMsg:(NSNotification*)no
{
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
    if (!self.recieveMsg) return;
    NSLog(@"------>收到设备信息:%@",dic);
        
        //消息是读还是写回复
        int answerType = [dic[CMD_CODE] intValue];
        if(answerType == 0x03){
            RHLocalSettingModel *readModel = [self.cmdArray firstObject];
            
            if(readModel.regAddr == [dic[CMD_ADDRESS] integerValue]){
                NSData *data = dic[CMD_ADDRESS_VALUE];
                //写回复
               NSString *parse_content = [CBLEDataParse parseData:data settingModel:readModel];
                self.deviceId = parse_content;
//                [self checkDeviceId];
                NSLog(@"----->设备ID:%@",parse_content);
            }
        }
        
        if(answerType == 0x10){
            RHLocalSettingModel *writeModel = [self.cmdArray lastObject];
            
            if(writeModel.regAddr == [dic[CMD_ADDRESS] integerValue]){
                //写回复
                [self.navigationController pushViewController:[BLEConnectClouldVC new] animated:YES];
            }
        }
        
        if(answerType == 0x90){
            //设置失败
            [QMUITips hideAllTips];
        }
        
  
}


- (void)setupUI{
    kWeakSelf;
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.backgroundColor = CFTabViewBgColor;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = CFTabViewBgColor;
    [scrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.offset(kUI_WINDOW_W);
    }];
    
    UIImageView *stepImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_config_step2"]];
    stepImg.contentMode = UIViewContentModeScaleAspectFit;
    [contentView addSubview:stepImg];
    [stepImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.width.offset(kScaleW(120));
        make.height.offset(40);
        make.centerX.mas_offset(0);
    }];

    
    UIImageView *connectStateImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_connected2"]];
    connectStateImg.contentMode = UIViewContentModeScaleAspectFit;
    [contentView addSubview:connectStateImg];
    [connectStateImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(stepImg.mas_bottom).offset(30);
        make.width.mas_offset(kScaleW(279));
        make.height.mas_offset(kScaleW(113));
        make.centerX.mas_offset(0);
    }];
    
    UIImageView *successImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_connect_success"]];
    successImg.contentMode = UIViewContentModeCenter;
    [contentView addSubview:successImg];
    [successImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(35);
        make.height.offset(35);
        make.centerX.equalTo(connectStateImg);
        make.top.equalTo(connectStateImg.mas_bottom).offset(30);
    }];
    
    QMUILabel *stateLab = [[QMUILabel alloc]init];
    stateLab.text = @"设备已连接网络".rh_localized;
    stateLab.textColor = kRGB(63, 68, 67);
    stateLab.font = kSYSTEMFONT(16);
    stateLab.numberOfLines = 0;
    stateLab.textAlignment = NSTextAlignmentCenter;
    [contentView addSubview:stateLab];
    [stateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(successImg.mas_bottom).offset(10);
    }];
    
    QMUILabel *tipsLab = [[QMUILabel alloc]init];
    tipsLab.text = @"此时，您可以根据需要将设备接入云端。可以随时随地了解设备状态，查看设备数据。".rh_localized;
    tipsLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    tipsLab.font = kSYSTEMFONT(12);
    tipsLab.textAlignment = NSTextAlignmentCenter;
    tipsLab.numberOfLines = 0;
    [contentView addSubview:tipsLab];
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(stateLab.mas_bottom).offset(15);
       
    }];
    
    QMUILabel *scrTitleLab = [[QMUILabel alloc]init];
    scrTitleLab.text = @"设置密钥".rh_localized;
    scrTitleLab.textColor = kColorRGBA(63, 68, 67, 1);
    scrTitleLab.font = kSYSTEMFONT(16);
    [contentView addSubview:scrTitleLab];
    [scrTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.top.equalTo(tipsLab.mas_bottom).offset(80);
    }];
    
    QMUIButton *helpBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [contentView addSubview:helpBtn];
    [helpBtn setImage:[UIImage imageNamed:@"secret_help"] forState:UIControlStateNormal];
    [helpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(35);
        make.left.equalTo(scrTitleLab.mas_right).offset(0);
        make.centerY.equalTo(scrTitleLab);
    }];
    
    _secretTextField = [[QMUITextField alloc] init];
    _secretTextField.backgroundColor = UIColor.whiteColor;
    _secretTextField.layer.cornerRadius = 8;
    _secretTextField.placeholder = @"请输入设备密钥".rh_localized;
    _secretTextField.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    _secretTextField.font = kSYSTEMFONT(14);
    _secretTextField.text = self.secret;
    [contentView addSubview:_secretTextField];
    
    
    UIView *pwdRightView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 40, 35)];
    QMUIButton *scanBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [pwdRightView addSubview:scanBtn];
    [scanBtn setImage:[UIImage imageNamed:@"input_scan_icon"] forState:UIControlStateNormal];
    _secretTextField.rightViewMode = UITextFieldViewModeAlways;
    _secretTextField.rightView = pwdRightView;
    [_secretTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(scrTitleLab.mas_bottom).offset(15);
        make.height.mas_equalTo(45);
    }];
    
    
    QMUIButton *seeBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
    [contentView addSubview:seeBtn];
    [seeBtn setTitle:@"查看设备密钥>>>".rh_localized forState:UIControlStateNormal];
    [seeBtn setTitleColor:kColorRGBA(63, 68, 67, 0.8) forState:UIControlStateNormal];
    seeBtn.titleLabel.font = kSYSTEMFONT(12);
    [seeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.secretTextField).offset(0);
        make.top.equalTo(weakSelf.secretTextField.mas_bottom).offset(10);
    }];
    
    _agreeBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_agreeBtn setImage:[UIImage imageNamed:@"remeber_normal"] forState:UIControlStateNormal];
    [_agreeBtn setImage:[UIImage imageNamed:@"remeber_selected"] forState:UIControlStateSelected];
    [contentView addSubview:_agreeBtn];
    [_agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(seeBtn.mas_bottom).offset(30);
        make.left.mas_offset(10);
        make.width.height.mas_offset(30);
    }];
    
    YYLabel *contentL = [[YYLabel alloc] init];
    NSString *str = [NSString stringWithFormat:@"%@%@",@"请仔细阅读并同意".rh_localized,@"《设备入网协议》".rh_localized];
    //设置多行
    contentL.numberOfLines = 0;
    //这个属性必须设置，多行才有效
    contentL.preferredMaxLayoutWidth = SCREEN_WIDTH-60;
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:str];
//    attri.yy_lineSpacing = 8;
    attri.yy_alignment = NSTextAlignmentLeft;
    attri.yy_font = kSYSTEMFONT(12);
    //FontColor(@"#3ECE80")
    attri.yy_color = kColorRGBA(63, 68, 67, 0.8);
    NSRange range1 = [str rangeOfString:@"《设备入网协议》".rh_localized];

    [attri yy_setTextHighlightRange:range1 color:kRGB(86, 194, 113) backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf.navigationController pushViewController:[RHBaseWebViewController new] animated:YES];
    }];
    
    //用label的attributedText属性来使用富文本
    contentL.attributedText = attri;
    CGSize maxSize = CGSizeMake(SCREEN_WIDTH-60, MAXFLOAT);
    //计算文本尺寸
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:attri];
    contentL.textLayout = layout;
    [contentView addSubview:contentL];
    [contentL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.agreeBtn.mas_right).offset(0);
        make.right.mas_offset(-15);
        make.centerY.equalTo(weakSelf.agreeBtn);
    }];
    
    QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(0, 0, 204, 45)];
    [btn setBackgroundColor:UIColor.blackColor];
    [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [btn setTitle:@"确认".rh_localized forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [btn.layer setCornerRadius:8];
    [btn setGradientBackgroundWithColors:@[kRGB(106, 215, 133),kRGB(94, 203, 183)] locations:@[@(0),@(1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5)];
    [contentView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.top.equalTo(contentL.mas_bottom).offset(15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(-20);
    }];
    
    
    [[helpBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf showTipsViewWithContent:@"设备密钥是每台设备对应的入网凭证，在我的设备列表中-设备信息，可以找到设备密钥。设备密钥为机密信息，请妥善保存。".rh_localized];
    }];
    
    [[seeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
       
    }];
    
    [[scanBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf scanQRC];
    }];
    
    [[_agreeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        x.selected = !x.selected;
    }];
    
#pragma mark ------ 写入密钥
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (!weakSelf.agreeBtn.selected) {
            [QMUITips showInfo:@"请阅读并同意入网协议".rh_localized];
            return;
        }
        if(weakSelf.secretTextField.text.length == 0){
            [QMUITips showError:@"请输入设备密钥".rh_localized];
            return;
        }
        RHLocalSettingModel *writeModel = [weakSelf.cmdArray lastObject];
        writeModel.content = weakSelf.secretTextField.text;
        [[RHBleCmdManager shareMnger]writeDeviceInfoFromBle:@[writeModel]];
    }];
}

-(void)showTipsViewWithContent:(NSString *)tips
{
    UIView *bgView = kView;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.layer.shadowColor = [UIColor grayColor].CGColor;
    contentView.layer.shadowRadius = 5;
    contentView.layer.shadowOpacity = 0.5;
    contentView.layer.cornerRadius = 8;
    contentView.layer.shadowOffset = CGSizeMake(0, 2);
    [bgView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(25);
        make.right.mas_offset(-25);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *tipsLab = [[QMUILabel alloc]init];
    tipsLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    tipsLab.text = tips;
    tipsLab.font = kSYSTEMFONT(12);
    tipsLab.textAlignment = NSTextAlignmentCenter;
    tipsLab.numberOfLines = 0;
    tipsLab.qmui_lineHeight = 25;
    [contentView addSubview:tipsLab];
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.mas_offset(15);
    }];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"知道了".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:kRGB(86, 194, 113) forState:UIControlStateNormal];
    sureBtn.titleLabel.font = kSYSTEMFONT(14);
    [contentView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(tipsLab.mas_bottom).offset(20);
        make.centerX.mas_offset(0);
        make.bottom.mas_offset(-15);
    }];
    
    
    kWeakSelf;
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [bgView removeFromSuperview];
    }];
}

//扫二维码
- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
                    weakSelf.secretTextField.text = content;
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"请在系统设置中打开相册使用权限");
        }else{
            result(NO,@"请在系统设置中打开摄像头使用权限");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}




@end
